//https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/submissions/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> ans, tmp;
        dfs(ans, root, 0);
        for(int i = ans.size() - 1; i >=0; i--)
        {
            tmp.push_back(ans[i]);
        }
        return tmp;
    }
    void dfs(vector<vector<int>>& ans, TreeNode* root, int level)
    {
        if(root == nullptr) return;
        if(level >= ans.size())
        {
            ans.push_back(vector<int>());
        }
        ans[level].push_back(root->val);
        dfs(ans, root->left, level + 1);
        dfs(ans, root->right, level + 1);
    }
};